const { query } = require("express");
let dbConfig = require("../utils/dbconfig");

// 获取分类- 不需要传参
getCate = (req, res) => {
  let sql = "select id,category,status,create_time from cate";
  let sqlArr = [];
  let callBack = (err, data) => {
    if (err) {
      res.send({
        message: "连接错误",
      });
    } else {
      res.send({
        list: data,
      });
    }
  };
  // 调用 sql 连接池回调
  dbConfig.sqlConnect(sql, sqlArr, callBack);
};

// 获取指定分类id查询文章列表
getPostCate = (req, res) => {
  let { id } = req.query;
  let sql = "select * from article where cate_id=?";
  let sqlArr = [id];
  let callBack = (err, data) => {
    if (err) {
      res.send({
        code: 500,
        message: "获取失败",
      });
    } else {
      res.send({
        list: data,
      });
    }
  };
  // 调用 sql 连接池回调
  dbConfig.sqlConnect(sql, sqlArr, callBack);
};

// 删除文章
deleteArticle = (req, res) => {
  let { id } = req.query;
  let sql = "delete from article where id=?";
  let sqlArr = [id];
  let callBack = (err, data) => {
    if (err) {
      res.send({
        code: 500,
        message: "删除失败",
      });
    } else {
      res.send({
        code: 200,
        message: "删除成功",
      });
    }
  };
  dbConfig.sqlConnect(sql, sqlArr, callBack);
};

// 添加文章
addArticle = async (req, res) => {
  let { title, descs, type, content, cate_id } = req.query;
  let sql =
    "insert into article (title,descs,type,content,cate_id,treate_time) values(?,?,?,?,?,?)";
  let sqlArr = [title, descs, type, content, cate_id, new Date().valueOf()];
  // TODO：判断排序字段值是否重复，重复则提示
  let article_id = await dbConfig
    .SySqlConnect(sql, sqlArr)
    .then((res) => {
      return res.insertId;
    })
    .catch((err) => {
      return false;
    });
  // 添加后判断id是否存在
  if (article_id) {
    res.send({
      code: 200,
      msg: "添加成功",
    });
  } else {
    res.send({
      code: 500,
      msg: "添加失败",
    });
  }
};

// 编辑文章
editArticle = async (req, res) => {
  let { title, descs, type, content, cate_id, id } = req.query;
  if (id) {
    let sql =
      "update article set title=?,descs=?,type=?,content=?,cate_id=?,treate_time=? where id=?";
    let sqlArr = [
      title,
      descs,
      type,
      content,
      cate_id,
      new Date().valueOf(),
      id,
    ];
    let result = await dbConfig.SySqlConnect(sql, sqlArr);
    if (result.affectedRows == 1) {
      res.send({
        code: 200,
        message: "修改成功",
      });
    } else {
      res.send({
        code: 500,
        message: "修改失败",
      });
    }
  } else {
    res.send({
      code: 500,
      message: "文章id不能为空",
    });
  }
};

module.exports = {
  getCate,
  getPostCate,
  addArticle,
  editArticle,
  deleteArticle,
};
